package keter.combofs.util;

import com.google.common.base.Charsets;
import com.google.common.io.Files;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.ClassPathResource;

import java.io.File;
import java.io.IOException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * 
 */
public class IOUtil {
    private static final Logger logger = LoggerFactory.getLogger(IOUtil.class);

    /**
     * <p>
     * Method ：ensureExists
     * <p>
     * Description : 确保路径存在
     *
     * @param path
     * @author 顾力行-gulixing@msn.com
     */
    public static String ensureExists(String path) {
        if (!new File(path).exists()) {
            boolean dir = new File(path).mkdirs();
            if(!dir){
                logger.error("无法创建目录:{}",path);
                throw new RuntimeException("目录["+path+"]创建失败！");
            }
        }
        return path;
    }
    
    public static boolean existsFile(String path) {
    	return new  File(path).exists();
    }

    public static boolean existsClassPathFile(String path) {
       return new ClassPathResource(path).exists();
    }

    public static byte[] toByteArray(File f) {
    	try {
			return Files.toByteArray(f);
		} catch (IOException e) {
			logger.error("",e);
		}
    	return null;
    }
    
    public static String fileToString(String fileUri) throws IOException {
        return Files.asCharSource(new File(fileUri), Charsets.UTF_8).read();
    }
    
    public static long sizeOf(String fileUri) throws IOException {
          return sizeOf(new File(fileUri));
    }
    
    public static long sizeOf(File file) throws IOException {
		  return Files.asByteSource(file).size();
    }
    
    public static long bytesToMB(long bytes){
    	return bytes/1024/1024;
    }

    
    /**
     * <p>Method ：writeFile
     * <p>Description : 字节数组写入磁盘文件
     * @param b
     * @param outputFile 
     * @author  gulixing@msn.com
     * @version 1.0.0
     */
    public static void writeFile(byte[] b, String outputFile) {
    	try {
			Files.write(b, new File(outputFile));
		} catch (IOException e) {
			logger.error("",e);
		}
    }

    private final static String[] strHex = { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f" };

    public static String getMD5(String fileUri) {
        return getMD5(toByteArray(new File(fileUri)));
    }

    public static String getMD5(byte[] bytes) {
        StringBuffer sb = new StringBuffer();
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            byte[] b = md.digest(bytes);
            for (int i = 0; i < b.length; i++) {
                int d = b[i];
                if (d < 0) {
                    d += 256;
                }
                int d1 = d / 16;
                int d2 = d % 16;
                sb.append(strHex[d1] + strHex[d2]);
            }
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return sb.toString();
    }
}